function makeCasesRequest(account_id) {    
	var params = {};
	var html=''; 
	jQuery('#cases-box').hide(); 
	jQuery('#loading-cases').show();             	
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
	var url = "http://crm.slaterhq.com/custom/calendar_sync/accounts.php?method=case&account_id="+account_id;
	makeCachedRequest(url, response_cases, params);
};

function count_cases(data){
	var key, count = 0; 
	for(key in data) {
		count++;
	}         
	return count;
}

function response_cases(obj) { 
	var jsondata =obj.data;                  
	var html='';                     
	var count=count_cases(jsondata);        
	if(count){                              	
		html += "<option value='-1'>Please Select</option>";	
		for (var key in jsondata) {
			var value = jsondata[key];			             								
			if (value instanceof Array)
			{								  
				html += "<option value='"+value.id+"'>"+ value.name +"</option>";		
			} 								
			else {        
				html += "<option value='"+value.id+"'>"+ value.name +"</option>";			
			}      
		}          
	}else{
		html += "<option value='-1'>No cases found</option>";			       
	}              			  
	jQuery('#account_case').html(html);
	jQuery('#loading-cases').hide();      
	jQuery('#cases-box').show();            				 
};

function makeCachedRequest(url, callback, params, refreshInterval) {
	var ts = new Date().getTime();
	var sep = "?";
	if (refreshInterval && refreshInterval > 0) {
		ts = Math.floor(ts / (refreshInterval * 1000));
	}
	if (url.indexOf("?") > -1) {
		sep = "&";
	}
	url = [ url, sep, "nocache=", ts ].join("");
	gadgets.io.makeRequest(url, callback, params);
}

function makeJSONRequest() {  
	var params = {};	    
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
	var url = "http://crm.slaterhq.com/custom/calendar_sync/account.txt";
	makeCachedRequest(url, response_account, params);
};

function response_account(obj) { 
	var jsondata =obj.data;           
	var html='';	
	html="<option value='-1'>Please Select</option>";						
	jQuery('#account_case').html("<option value='-1'>Please select</option>");                    
	for (var key in jsondata) {
		var value = jsondata[key];								
		if (value instanceof Array)
		{								  
			html += "<option value='"+value.id+"'>"+ value.name +"</option>";		
		} 								
		else {        
			html += "<option value='"+value.id+"'>"+ value.name +"</option>";			
		}      
	}         						   					    					    
	jQuery('#account').html(html);							
};			

var calender = null;
var author_email = null;

function initGadget() {	        					
	google.load('gdata', '2.x');
	google.setOnLoadCallback(function () {
	calender = new google.gdata.calendar.CalendarService('slater-calender');            
	calender.useOAuth('google');
	fetchData();
	});
}

function showOnly(id) {
	var sections = ['main', 'approval', 'waiting', 'loading', 'errors'];
	for (var i = 0, section; section = sections[i]; ++i) {
		jQuery('#' + section).get(0).style.display = section === id ? 'block' : 'none';
	}
}

function fetchData() {
	jQuery('#errors').hide();

	var callback = function(response) {                          
		if(response.oauthApprovalUrl) {                          
			var popup = shindig.oauth.popup({
			destination: response.oauthApprovalUrl,
			windowOptions: 'height=600,width=800',
			onOpen: function() {
			showOnly('waiting');
			},
			onClose: function() {
			showOnly('loading');                  
			fetchData();
			}
		});
		jQuery('#personalize').get(0).onclick = popup.createOpenerOnClick();
		jQuery('#approvalLink').get(0).onclick = popup.createApprovedOnClick();                
		showOnly('approval');
		} else if (response.feed) {            
			var userEmail=response.feed.author[0].email.$t;               
			var user_domain=userEmail.split("@"); 
			if(user_domain[1] == domain){                              						
			showOnly('main');                
			makeJSONRequest();
			document.getElementById('userEmail').value=userEmail;
		}else{
			jQuery('#errors').html('Authentication Failed!').fadeIn();
			showOnly('errors');
		}	
		} else {
			jQuery('#errors').html('Something went wrong').fadeIn();
			showOnly('errors');
		}
	};		

	calender.getEventsFeed('http://www.google.com/calendar/feeds/default/private/full', callback, callback);
};   

function saveEvent(form){
	jQuery('#errors').hide();
	var author_email=document.getElementById('userEmail').value; 														
	var feedUri = 'http://www.google.com/calendar/feeds/default/private/full';	
	console.log(feedUri);				
	var entry = new google.gdata.calendar.CalendarEventEntry();
	var subject=form.account.options[form.account.selectedIndex].text+'-'+form.account_case.options[form.account_case.selectedIndex].text;
	entry.setTitle(new google.gdata.atom.Text.create(subject));

	entry.setContent(new google.gdata.atom.Text.create(form.comment.value));

	// Create a When object that will be attached to the event
	var when = new google.gdata.When();

	// Set the start and end time of the When object
	var startTime = google.gdata.DateTime.fromIso8601(form.from_date.value);
	var endTime = google.gdata.DateTime.fromIso8601(form.to_date.value);
	when.setStartTime(startTime);
	when.setEndTime(endTime);

	entry.addTime(when);	        

	var extendedProp = new google.gdata.ExtendedProperty();					
	extendedProp.setName('Gadget');					
	extendedProp.setValue('Google Calender Gadget');					
	entry.addExtendedProperty(extendedProp);

	var extendedProp2 = new google.gdata.ExtendedProperty();					
	extendedProp2.setName('case_id');					
	extendedProp2.setValue(form.account_case.options[form.account_case.selectedIndex].value);					
	entry.addExtendedProperty(extendedProp2);
   
	    //console.log(entry);

	var handleMyInsertedEntry = function(feedRoot) {                 
		//var entry_id=feedRoot.entry.getSelfLink().getHref();     
		//var startdate=document.getElementById('from_date').value;
		//var params = {};
		//var postdata = {
		//method:'save',
		//email:document.getElementById('userEmail').value,
		//outlook_id:feedRoot.entry.getSelfLink().getHref(),
		//title :feedRoot.entry.getTitle().getText(),
		//comment:feedRoot.entry.getContent().getText(),
		//startdate:document.getElementById('from_date').value,
		//enddate:document.getElementById('to_date').value,
		//case_id : form.account_case.options[form.account_case.selectedIndex].value                                
		//}; 
		//postdata = gadgets.io.encodeValues(postdata);
		//params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
		//params[gadgets.io.RequestParameters.POST_DATA]= postdata;
		//url='http://crm.slaterhq.com/custom/calendar_sync/accounts.php';
		//gadgets.io.makeRequest(url, response_save, params);
		jQuery('#messages').html('Data Successfully saved!').fadeIn(); 			     
		setTimeout(form.reset(),5000); 	
		jQuery('#loading-cases').hide();      
		jQuery('#cases-box').hide();              
		google.calendar.refreshEvents();
	};

	    var response_save = function(obj) {                 
		jQuery('#submitButton').val('Save').removeAttr('disabled');
	};

	var insertIntoMyFeed = function(feedRoot) {
		var newEntry = new google.gdata.calendar.CalendarEventEntry({
			title: {
			type: 'text', 
			text: 'test event'
			},
			content: {
			type: 'text', 
			text: 'Meet for a quick lesson'
			},
			locations: [{
			rel: "g.event",
			label: "Event location",
			valueString: "Netherfield Park tennis court"
			}],
			times: [{
			startTime: google.gdata.DateTime.fromIso8601("2007-09-23T18:00:00.000Z"),
			endTime: google.gdata.DateTime.fromIso8601("2007-09-23T19:00:00.000Z")
			}]
		});
		feedRoot.feed.insertEntry(newEntry, handleMyInsertedEntry, handleError);
	};

	var handleMyFeed = function(feedRoot) { 		  
		insertIntoMyFeed(myResultsFeedRoot);
	}

	var handleError = function(e) {
		var msg = e.cause ? e.cause.statusText + ': ' : '';
		msg += e.message;
		jQuery('#messages').html('Post published! ' + msg).fadeIn();
	};

	if(form.account_case.value != '-1' && form.from_date.value != null && form.to_date.value != null && form.account.value != '-1' && form.comment.value != null)		
	{	    
		calender.insertEntry(feedUri, entry, handleMyInsertedEntry, handleError, google.gdata.calendar.CalendarEventEntry);
	}else{
		jQuery('#messages').html('Event not created- All fields are required ').fadeIn();
	}	  										
};
gadgets.util.registerOnLoadHandler(initGadget);
